<template>
  <div>
    <!--    <el-card :bordered="false" shadow="never" class="ivu-mb-16" :body-style="{padding:0}">-->
    <!--      <div class="padding-add">-->
    <!--        <el-form-->
    <!--          ref="artFrom"-->
    <!--          :model="artFrom"-->
    <!--          :label-width="labelWidth"-->
    <!--          label-position="right"-->
    <!--          @submit.native.prevent-->
    <!--          inline-->
    <!--        >-->
    <!--          <el-form-item label="文章分类：" label-for="pid">-->
    <!--            <el-cascader-->
    <!--              v-model="artFrom.pid"-->
    <!--              placeholder="请选择"-->
    <!--              class="treeSel"-->
    <!--              @change="handleCheckChange"-->
    <!--              :options="treeData"-->
    <!--              :props="props"-->
    <!--              style="width: 250px"-->
    <!--            >-->
    <!--            </el-cascader>-->
    <!--          </el-form-item>-->
    <!--          <el-form-item label="文章搜索：" label-for="title">-->
    <!--            <el-input-->
    <!--              clearable-->
    <!--              placeholder="请输入"-->
    <!--              v-model="artFrom.title"-->
    <!--              class="form_content_width"-->
    <!--            />-->
    <!--          </el-form-item>-->
    <!--          <el-form-item>-->
    <!--            <el-button type="primary" @click="userSearchs">查询</el-button>-->
    <!--          </el-form-item>-->
    <!--        </el-form>-->
    <!--      </div>-->
    <!--    </el-card>-->
    <el-card :bordered="false" shadow="never" class="ivu-mt">
      <div class="top-box">
        <el-button type="primary" class="bnt" @click="addArticle">添加服务</el-button>
        <div class="carouse">
          <span>状态：</span>
          <el-select v-model="serviceTypeValue" placeholder="请选择" @change="carouseChange">
            <el-option
              v-for="item in serviceTypeList"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <el-table
        :data="cmsList"
        ref="table"
        class="mt14"
        v-loading="loading"
        highlight-current-row
        no-userFrom-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
      >
        <el-table-column label="ID" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="封面图" min-width="60">
          <template slot-scope="scope">
            <div v-if="scope.row.cover" v-viewer>
              <div class="tabBox_img">
                <img v-lazy="scope.row.cover" />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="类型" min-width="60">
          <template slot-scope="scope">
            <span>{{ scope.row.cate_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题" min-width="130">
          <template slot-scope="scope">
<!--            <el-tooltip placement="top" :open-delay="600">-->
<!--              <div slot="content">{{ " [ " + scope.row.title + " ] " + scope.row.title }}</div>-->
              <span class="line2">{{ scope.row.title }}</span>
<!--            </el-tooltip>-->
          </template>
        </el-table-column>
        <el-table-column label="价格" min-width="60">
          <template slot-scope="scope">
            <span>{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="60">
          <template slot-scope="scope">
            <span v-if="scope.row.status === 1">已上架</span>
            <span v-if="scope.row.status === 0">未上架</span>
          </template>
        </el-table-column>

        <el-table-column label="库存" min-width="60">
          <template slot-scope="scope">
            <span>{{ scope.row.stock }}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用次数" min-width="60">
          <template slot-scope="scope">
            <span>{{ scope.row.frequency_of_use }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.add_time }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="170">
          <template slot-scope="scope">
            <a @click="edit(scope.row)">编辑</a>
                        <el-divider direction="vertical"></el-divider>
                        <a @click="artRelation(scope.row)">关联</a>
            <el-divider direction="vertical"></el-divider>
            <a @click="del(scope.row, '删除服务信息', scope.$index)">删除</a>
          </template>
        </el-table-column>
      </el-table>
      <div class="acea-row row-right page">
        <pagination
          v-if="total"
          :total="total"
          :page.sync="artFrom.page"
          :limit.sync="artFrom.limit"
          @pagination="getList"
        />
      </div>
    </el-card>


    <div class="adddistribution-box" v-if="addclassification">
      <div class="title-box">
        <div class="header">
          <div class="left-text">{{ popupTitle }}</div>
          <div class="right-icon"><i class="el-icon-close" style="font-size: 23px;color: #999;" @click="cancelK"></i>
          </div>
        </div>
        <div class="center-box">
          <el-form :model="classificationList" :rules="rules" ref="classificationList" label-width="100px"
                   class="demo-dynamic">
            <el-form-item prop="title" label="类型:" style="margin-top: 20px">
              <el-select v-model="classificationList.cate_id" placeholder="请选择">
                <el-option
                  v-for="item in typeList"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="title" label="服务名称:" style="margin-top: 20px">
              <el-input v-model="classificationList.title" style="width: 90%" placeholder="请输入服务名称"></el-input>
            </el-form-item>
            <el-form-item prop="introduce" label="服务介绍:" style="margin-top: 20px">
              <el-input
                type="textarea" style="width: 90%" :rows="2" placeholder="请输入介绍内容"
                v-model="classificationList.introduce"></el-input>
            </el-form-item>
            <el-form-item prop="content" label="服务详情:" style="margin-top: 20px">
              <el-input
                type="textarea" style="width: 90%" :rows="2" placeholder="请输入详情内容"
                v-model="classificationList.content"></el-input>
            </el-form-item>

            <div class="item-box">
              <el-form-item prop="price" label="价格:">
                <el-input v-model="classificationList.price" style="width: 60%" placeholder="请输入价格"></el-input>
              </el-form-item>
              <el-form-item prop="stock" label="库存:">
                <el-input v-model="classificationList.stock" style="width: 60%" placeholder="请输入库存"></el-input>
              </el-form-item>
            </div>


            <div class="item-box">
              <el-form-item prop="frequency_of_use" label="使用次数:">
                <el-input v-model="classificationList.frequency_of_use" style="width: 60%"
                          placeholder="请输入次数"></el-input>
              </el-form-item>
              <el-form-item prop="purchase_restriction" label="限购:">
                <el-input v-model="classificationList.purchase_restriction" style="width: 60%"
                          placeholder="请输入数量"></el-input>
              </el-form-item>
            </div>

            <div class="item-box">
              <el-form-item prop="one_commission_ratio" label="一级分佣:">
                <el-input v-model="classificationList.one_commission_ratio" style="width: 60%"
                          placeholder="请输入比例"></el-input>%
              </el-form-item>
              <el-form-item prop="two_commission_ratio" label="二级分佣:">
                <el-input v-model="classificationList.two_commission_ratio" style="width: 60%"
                          placeholder="请输入比例"></el-input>%
              </el-form-item>
            </div>

            <el-form-item label="状态：">
              <el-radio-group v-model="classificationList.status" class="form-sty">
                <el-radio :label="1">已上架</el-radio>
                <el-radio :label="0">未上架</el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="item-box">
              <el-form-item class="form" label="封面图：">
                <div class="picBox" @click="modalPicTap('单选')">
                  <div class="pictrue" v-if="classificationList.cover">
                    <img :src="classificationList.cover" />
                  </div>
                  <div v-else class="upLoad acea-row row-center-wrapper">
                    <i class="el-icon-plus" style="font-size: 24px"></i>
                  </div>
                </div>
                <div class="tip">只能上传一张图片</div>
              </el-form-item>
              <el-form-item class="form" label="轮播图：" style="flex: 1">
                <div class="acea-row">
                  <template>
                    <div class="pictrue" style="margin-bottom: 10px" v-for="(item, index) in classificationList.imgs"
                         :key="index" draggable="true" >
                      <img :src="item" />
                      <i class="el-icon-error btndel" @click="handleRemove(index)"></i>
                    </div>
                  </template>
                  <div  class="upLoad acea-row row-center-wrapper"
                       @click="modalPicTap('多选')" v-if="classificationList.imgs.length < 5">
                    <i class="el-icon-plus" style="font-size: 24px"></i>
                  </div>
                  <!--                  <el-input v-model="formValidate.slider_image[0]" style="display: none"></el-input>-->
                </div>
                <div class="tip">最多上传5张图片</div>

                <!--                <div class="picBox" @click="modalPicTap('多选')" >-->
                <!--                  <div class="pictrue" v-if="classificationList.imgs.length>0" >-->
                <!--                    <template v-for="(item, index) in classificationList.imgs" style="display: flex; flex-direction:column" >-->
                <!--                      <img :src="item" style="margin-right: 10px"/>-->
                <!--                    </template>-->
                <!--                  </div>-->
                <!--                  <div v-else class="upLoad acea-row row-center-wrapper">-->
                <!--                    <i class="el-icon-plus" style="font-size: 24px"></i>-->
                <!--                  </div>-->
                <!--                </div>-->
              </el-form-item>
            </div>
            <!--            <el-form-item class="form" label="封面图：">-->
            <!--              <div class="picBox" @click="modalPicTap('单选')">-->
            <!--                <div class="pictrue" v-if="classificationList.cover">-->
            <!--                  <img :src="classificationList.cover" />-->
            <!--                </div>-->
            <!--                <div v-else class="upLoad acea-row row-center-wrapper">-->
            <!--                  <i class="el-icon-plus" style="font-size: 24px"></i>-->
            <!--                </div>-->
            <!--              </div>-->
            <!--              <div class="tip">只能上传一张图片</div>-->
            <!--            </el-form-item>-->
          </el-form>
          <div class="button-box">
            <button class="cancel" @click="cancelK">取消</button>
            <button class="determine" v-if="modifyT" @click="determinadd">确定</button>
            <button class="determine" v-else @click="determinadd">修改</button>
          </div>
        </div>
        <el-dialog z-index="20" :visible.sync="modalPic" width="950px" title="上传分类图" :close-on-click-modal="false">
          <uploadPictures
            :isChoice="isChoice"
            @getPic="getPic"
            @getPicD="getPicD"
            :gridBtn="gridBtn"
            :gridPic="gridPic"
            v-if="modalPic"
          ></uploadPictures>
        </el-dialog>
      </div>
    </div>
    <!--关联-->
        <el-dialog :visible.sync="modals" title="关联服务" class="paymentFooter" width="1000px" @closed="cancel">
          <goods-list ref="goodslist" :Id="serviceId" :type="0" @closePop="cancel" @getProductId="getProductId"></goods-list>
        </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { cmsListApi, categoryListApi, relationApi } from "@/api/cms";
import { serviceListApi, serviceSaveApi, serviceCategoryListApi, serviceDelApi } from "@api/service_information";
// import relationList from './relation';
import { formatDate } from "@/utils/validate";
import uploadPictures from "@/components/uploadPictures";
import goodsList from "@/components/goodsList/serviceAssociation.vue";

export default {
  name: "cms_article",
  components: {
    uploadPictures,
    goodsList
  },
  data() {
    return {
      modalTitleSs: "",
      loading: false,
      artFrom: {
        page: 1,
        limit: 20,
        status:'',
      },
      total: 0,
      addclassification: false,
      modalPic: false,
      modifyT: true,
      images: [],
      popupTitle: "添加服务",
      serviceId: null,
      typeList: [], // 分类列表
      serviceTypeValue:'',  //  选择状态
      serviceTypeList:[
        {id:"",label:"全部"},
        {id:1,label:"已上架"},
        {id:0,label:"未上架"},
      ],
      classificationList: {
        id: "",
        title: "",  //  标题
        cate_id: null, // 分类id
        cover: "", // 封面图
        purchase_restriction: null, // 限购
        introduce: "", // 服务介绍
        add_time: "", // 时间
        sale: null, // 虚拟销量
        content: "", // 服务详情
        sort: 0, // 排序
        one_commission_ratio: null, // 一级分佣比例(%)
        two_commission_ratio: null, // 二级分佣比例(%)
        price: null, // 价格
        stock: null, // 库存
        frequency_of_use: null, // 使用次数
        status: 1,//  是否上架
        imgs: [] // 图片列表
      },
      isChoice: "",
      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12
      },
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8
      },
      cmsList: [],
      treeData: [],
      list: [],
      cid: 0, // 移动分类id
      cmsId: 0,
      formValidate: {
        type: 1
      },
      rows: {},
      modal_loading: false,
      modals: false,
      props: {
        value: "id",
        label: "title",
        emitPath: false
      },
      rules: {
        title: [
          { required: true, message: "请输入服务名称", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        introduce: [
          { required: true, message: "服务介绍", trigger: "blur" }
          // { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        content: [
          { required: true, message: "服务详情", trigger: "blur" }
          // { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        price: [
          { required: true, message: "请输入价格", trigger: "blur" },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入数字，最多两位小数", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "请输入价格", trigger: "blur" },
          { pattern: /^[0-9]*$/, message: "请输入整数", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        purchase_restriction: [
          { required: true, message: "请输入限购数量", trigger: "blur" },
          { pattern: /^[0-9]*$/, message: "请输入整数", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        one_commission_ratio: [
          { required: true, message: "请输入一级分佣", trigger: "blur" },
          { pattern: /^[0-9]*$/, message: "请输入整数", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        two_commission_ratio: [
          { required: true, message: "请输入二级分佣", trigger: "blur" },
          { pattern: /^[0-9]*$/, message: "请输入整数", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        frequency_of_use: [
          { required: true, message: "请输入价格", trigger: "blur" },
          { pattern: /^[0-9]*$/, message: "请输入整数", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    ...mapState("media", ["isMobile"]),
    labelWidth() {
      return this.isMobile ? undefined : "80px";
    },
    labelPosition() {
      return this.isMobile ? "top" : "right";
    }
  },
  filters: {
    formatDate(time) {
      if (time !== 0) {
        let date = new Date(time * 1000);
        return formatDate(date, "yyyy-MM-dd hh:mm");
      }
    }
  },
  created() {
    this.getCategoryList();

  },
  activated() {
    // this.artFrom.pid = this.$route.query.id ? this.$route.query.id : 0;
    this.getList();
    this.getClass();
  },
  methods: {
    // 关联成功
    getProductId(row) {
      let data = {
        product_id: row.id
      };
      relationApi(data, this.rows.id)
        .then(async (res) => {
          this.$message.success(res.msg);
          row.id = 0;
          this.modal_loading = false;
          this.modals = false;
          setTimeout(() => {
            this.getList();
          }, 500);
        })
        .catch((res) => {
          this.modal_loading = false;
          this.loading = false;
          this.$message.error(res.msg);
        });
    },
    cancel() {
      this.modals = false;
    },
    // 服务信息列表
    getList() {
      this.loading = true;
      // console.log(this.artFrom, "参数参数参数参数参数参数");
      serviceListApi(this.artFrom)
        .then(async (res) => {
          let data = res.data;
          // console.log(data, "服务信息列表服务信息列表服务信息列表",this.typeList);
          this.cmsList = data.list;
          this.total = data.count;
          this.loading = false;
          this.cmsList.forEach(item => {
            const doctorType=this.typeList.find(item1=>item1.id===item.cate_id)
            if(doctorType){
              item.cate_name=doctorType.title
            }
          })
          // console.log(this.cmsList, "服务信息列表服1务信息列表服务信息列表");
        })
        .catch((res) => {
          this.loading = false;
          this.$message.error(res.msg);
        });
    },

    //  获取类型列表
    getCategoryList() {
      serviceCategoryListApi({ page: 1, limit: 100 }).then(res => {
        this.typeList = res.data;
      });
    },
    // 分类
    getClass() {
      categoryListApi(this.formValidate)
        .then(async (res) => {
          let data = res.data;
          this.treeData = data;
          let obj = {
            id: 0,
            title: "全部"
          };
          this.treeData.unshift(obj);
        })
        .catch((res) => {
          this.$message.error(res.msg);
        });
    },
    // 下拉树
    handleCheckChange(data) {
      // this.artFrom.pid = data ? data : 0;
      this.artFrom.page = 1;
      this.getList();
    },
    // 编辑
    edit(row) {
      console.log(row, "编辑编辑编辑编辑");
      this.modifyT = false;
      this.classificationList = JSON.parse(JSON.stringify(row));
      this.addclassification = true;
      this.popupTitle = "修改服务信息";
      // this.$router.push({ path: this.$routeProStr + '/cms/article/add_article/' + row.id });
    },
    // 关联
    artRelation(row) {
      this.serviceId=row.id;
      this.modals = true;
    },
    // 删除
    del(row) {
      console.log(row, "删除删除删除删除删除");
      serviceDelApi(row.id).then(res => {
        this.$message.success(res.msg);
        this.getList();
      });
    },
    // 选择图片
    modalPicTap(type) {
      this.isChoice = type;
      // if(this.isChoice === '多选' && this.classificationList.imgs.length>3)return this.$message.error('最多只能选择5张图片');
      // console.log(this.classificationList.imgs.length, "选择选择选择选择选择");
      this.modalPic = true;
    },
    // 选中单张图片
    getPic(pc) {
      console.log("选择是");
      if (this.isChoice === "单选") {
        this.classificationList.cover = pc.att_dir;
      } else if (this.isChoice === "多选") {
        this.classificationList.imgs = pc.att_dir;
      }
      this.modalPic = false;
    },
    // 获取多张图信息
    getPicD(pc) {
      this.images = pc;
      this.images.map((item) => {
        this.classificationList.imgs.push(item.att_dir);
        this.classificationList.imgs = this.classificationList.imgs.splice(0, 5);
      });
      this.modalPic = false;
    },
    // 打开添加服务信息弹窗
    addArticle() {
      // console.log("添加添加添加添加添加");
      this.addclassification = true;
      this.modifyT = true;
      this.popupTitle = "添加服务信息";
    },
    // 服务信息取消事件
    cancelK() {
      this.classificationList = {};
      this.classificationList.imgs=[]
      this.classificationList.status = 1;
      this.classificationList.sort = 0;
      this.addclassification = false;
    },

    // 服务信息确定事件or服务信息修改事件
    determinadd() {
      console.log("确定确定确定",this.classificationList.cate_id);
      if (this.classificationList.cate_id === "") return this.$message.error("请选择分类");
      if (this.classificationList.title === "") return this.$message.error("请输入服务名称");
      if (this.classificationList.introduce === "") return this.$message.error("请输入介绍内容");
      if (this.classificationList.content === "") return this.$message.error("请输入详情内容");
      if (this.classificationList.price === "") return this.$message.error("请输入价格");
      if (this.classificationList.stock === "") return this.$message.error("请输入库存");
      if (this.classificationList.frequency_of_use === "") return this.$message.error("请输入次数");
      if (this.classificationList.purchase_restriction === "") return this.$message.error("请输入数量");
      if (this.classificationList.one_commission_ratio === "") return this.$message.error("请输入比例");
      if (this.classificationList.two_commission_ratio === "") return this.$message.error("请输入比例");
      if (this.classificationList.cover === "") return this.$message.error("请上传封面");
      if(this.classificationList.imgs.length === 0) return this.$message.error('图片不能为空');
      serviceSaveApi(this.classificationList).then(res => {
        if (res.status === 200) {
          this.$message.success(res.msg);
          this.getList();
          this.$router.go(0); // 重新加载当前路由
        } else {
          this.$message.error(res.msg);
        }
      });
      this.classificationList = {};
      this.classificationList.imgs=[]
      this.classificationList.cate_id=""
      this.classificationList.status = 1;
      this.classificationList.sort = 0;
      this.addclassification = false;
    },
    //  删除轮播图列表的某一个元素
    handleRemove(i) {
      this.images.splice(i, 1);
      this.classificationList.imgs.splice(i, 1);
      // this.oneFormValidate[0].pic = this.formValidate.slider_image[0];
    },

    //  选择状态
    carouseChange(){
      this.artFrom.page = 1;
      this.artFrom.status = this.serviceTypeValue;
      this.getList()
    },
    // 表格搜索
    userSearchs() {
      this.artFrom.page = 1;
      this.getList();
    }
  }
};
</script>

<style scoped lang="stylus">
.treeSel ::v-deep .ivu-select-dropdown-list {
  padding: 0 10px !important;
  box-sizing: border-box;
}

.tabBox_img {
  width: 36px;
  height: 36px;
  border-radius: 4px;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }
}

.adddistribution-box {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, .2);
  z-index: 30;

  .title-box {
    box-sizing: border-box;
    width: 35%;
    background: #fff;
    border-radius: 10px;
    padding-bottom: 10px;

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      border-bottom: 1px solid #e8eaec;

      .left-text {
        font-size: 14px;
      }
    }
  }

  .item-box {
    width: 100%;
    display: flex;
    //justify-content: space-between;
  }

  .picBox {
    //width: 100%;
    //display: inline-block;
    //cursor: pointer;
    //border: 1px solid red;
  }

  .form .pictrue {
    width: 60px;
    height: 60px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    margin-right: 10px;
    position: relative;

    .btndel {
      position: absolute;
      z-index: 1;
      width: 20px !important;
      height: 20px !important;
      left: 45px;
      top: 1px;
    }
  }

  .form .upLoad {
    width: 60px;
    height: 60px;
    line-height: 60px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.02);
  }

  .form .pictrue img {
    width: 60px;
    height: 60px;
  }

  .button-box {
    width: 100%;
    text-align: end;
    padding-bottom: 10px;

    button {
      padding: 6px 13px;
      margin-right: 15px;
      border-radius: 5px;
      border: 1px solid rgba(0, 0, 0, .1);
      font-size: 13px;
    }

    .determine {
      background: #0256ff;
      color: #fff;
    }
  }

  .tip {
    //margin-top: 10px;
    color: #bbb;
    font-size: 12px;
  }
}
.top-box{
  display: flex;
  align-items: center;
  .carouse{
    margin-left: 50px;
    span{
      color: #666;
    }
  }
}
</style>
